/**
 *
 */
package com.leonzx.base.config.jim;

import com.leonzx.base.config.jim.command.LoginServiceProcessor;
import com.leonzx.base.config.jim.command.WsHandshakeServiceProcessor;
import com.leonzx.base.config.jim.init.HttpServerInit;
import com.leonzx.base.config.jim.listener.ImAioListener;
import com.leonzx.base.config.jim.listener.ImDemoGroupListener;
import com.leonzx.base.controller.layim.DefaultChatProcessor;
import com.leonzx.base.service.system.ChatBodyService;
import com.leonzx.base.service.system.OrdersService;
import com.leonzx.base.service.system.RoleService;
import com.leonzx.base.service.system.UserService;
import org.apache.commons.lang3.StringUtils;
import org.jim.common.Const;
import org.jim.common.ImConfig;
import org.jim.common.packets.Command;
import org.jim.server.ImServerStarter;
import org.jim.server.command.CommandManager;
import org.jim.server.command.handler.ChatReqHandler;
import org.jim.server.command.handler.HandshakeReqHandler;
import org.jim.server.command.handler.LoginReqHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.tio.core.ssl.SslConfig;

import java.util.Objects;

/**
 * 项目启动时启动JIM开始类
 *
 * @author WChao
 */
@Component
public class ImServerStart implements CommandLineRunner {
    private Logger logger = LoggerFactory.getLogger(ImServerStart.class);
    @Value("${jim.port}")
    public Integer port;
    @Value("${jim.page}")
    private String page;
    @Value("${jim.shedule}")
    private String shedule;
    @Value("${jim.isStore}")
    private String isStore;
    @Value("${jim.isCluster}")
    private String isCluster;
    @Value("${jim.isSsl}")
    private String isSsl;
    @Value("${jim.keyStorePath}")
    private String keyStorePath;
    @Value("${jim.keyStorePwd}")
    private String keyStorePwd;

    @Autowired
    private UserService userService;
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private ChatBodyService chatBodyService;

    /**
     * 开启SSL之前，你要保证你有SSL证书哦！
     *
     * @param imConfig
     * @throws Exception
     */
    private void initSsl(ImConfig imConfig) throws Exception {
        ImConfig.isSSL = isSsl;//是否开启SSL;
        if (Const.ON.equals(ImConfig.isSSL)) {//开启SSL
            String keyStoreFile = keyStorePath;
            String trustStoreFile = keyStorePath;
            if (StringUtils.isNotBlank(keyStoreFile) && StringUtils.isNotBlank(trustStoreFile)) {
                SslConfig sslConfig = SslConfig.forServer(keyStoreFile, trustStoreFile, keyStorePwd);
                imConfig.setSslConfig(sslConfig);
            }
        }
    }

    @Override
    public void run(String... strings) throws Exception {

        isStore = Objects.equals(isStore, "true") ? "on" : "off";
        isCluster = Objects.equals(isCluster, "true") ? "on" : "off";
        isSsl = Objects.equals(isSsl, "true") ? "on" : "off";

        ImConfig.isStore = isStore;//是否开启持久化;(on:开启,off:不开启)
        ImConfig.isCluster = isCluster;//是否开启集群;
        ImConfig imConfig = new ImConfig(null, port);
        HttpServerInit.init(imConfig, page);
        initSsl(imConfig);//初始化SSL;(开启SSL之前,你要保证你有SSL证书哦...)
        //ImgMnService.start();//启动爬虫爬取模拟在线人头像;
        imConfig.setImGroupListener(new ImDemoGroupListener());//设置群组监听器，非必须，根据需要自己选择性实现;
        ImServerStarter imServerStarter = new ImServerStarter(imConfig, new ImAioListener());

        /*****************start 以下处理器根据业务需要自行添加与扩展，每个Command都可以添加扩展,此处为demo中处理**********************************/
        HandshakeReqHandler handshakeReqHandler = CommandManager.getCommand(Command.COMMAND_HANDSHAKE_REQ, HandshakeReqHandler.class);
        handshakeReqHandler.addProcessor(new WsHandshakeServiceProcessor());//添加自定义握手处理器;
        LoginReqHandler loginReqHandler = CommandManager.getCommand(Command.COMMAND_LOGIN_REQ, LoginReqHandler.class);
        loginReqHandler.addProcessor(new LoginServiceProcessor(userService, ordersService, roleService));//添加登录业务处理器;
        ChatReqHandler chatReqHandler = CommandManager.getCommand(Command.COMMAND_CHAT_REQ, ChatReqHandler.class);
        chatReqHandler.addProcessor(new DefaultChatProcessor(chatBodyService));//添加聊天持久化处理器
        /*****************end *******************************************************************************************/
        imServerStarter.start();
        logger.info("JIM will be execute when the project was started *********************************!");
    }
}
